import axios from "axios";
// import 'element-plus/es/components/message/style/css' 官方导入的文件会覆盖掉初始颜色
import 'element-plus/theme-chalk/el-message.css'
import {ElMessage} from 'element-plus'

import { useUserStore } from "@/stores/user";
import router from "@/router";

const instance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 10000
})

// 拦截器
// 请求拦截
instance.interceptors.request.use(config => {
     // 1. 从pinia获取token数据
     const {userInfo: {token}} = useUserStore()
    //  console.log(token);
    if(token) {
        // 2. 按照后端的要求拼接token数据
        config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
}, err => Promise.reject(err))


// 响应拦截
instance.interceptors.response.use(res => {
    return res.data
}, err => {
    // 统一拦截错误
    ElMessage({
        type: 'warning',
        message: err.response.data.message
    })
     // 401token失效处理
    // 1. 清除本地用户数据
    // 2. 跳转登录页
    const {clearUserInfo} = useUserStore()
    if (err.response.status === 401) {
        clearUserInfo()
        router.push('/login')
    }
    
    
    return Promise.reject(err)
})


export default instance